package com.smartboot.plus.utils;

import com.smartboot.plus.exception.ServiceException;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;
import java.util.Base64;

public class SecurePasswordUtil {
    public static String hashPassword(String password, String salt, String algorithm, String saltType) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            byte[] input;

            switch (saltType.toLowerCase()) {
                case "prefix":
                    input = (salt + password).getBytes(StandardCharsets.UTF_8);
                    break;
                case "suffix":
                    input = (password + salt).getBytes(StandardCharsets.UTF_8);
                    break;
                default:
                    return password;

            }

            byte[] hash = digest.digest(input);
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("哈希失败", e);
        }
    }

}
